package com.ruoyi.web.controller.system;

import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.system.domain.*;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.Global;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.system.service.IHxDayReportService;
import com.ruoyi.system.service.IHxProjectService;
import com.ruoyi.web.controller.common.CommonController;

/**
 * 日报 信息操作处理
 */
@Controller
@RequestMapping("/system/hxDayReport")
public class HxDayReportController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    private String prefix = "system/hxDayReport";

    @Autowired
    private IHxDayReportService hxDayReportService;

    @Autowired
    private IHxProjectService hxProjectService;

    @RequiresPermissions("system:hxDayReport:view")
    @GetMapping()
    public String hxDayReport() {
        return prefix + "/hxDayReport";
    }
    
    @RequiresPermissions("system:reportStatistics:view")
    @GetMapping("/reportStatistics")
    public String reportStatistics() {
        return prefix + "/reportStatistics";
    }
    

    @GetMapping("/userChooseOne")
    public String userChooseOne(ModelMap mmap) {
        return "system/user/userChooseOne";
    }

    /**
     * 导出月报表
     *
     * @param month
     */
//@RequiresPermissions("system:monthReport:export")
/*    @PostMapping("/export")
@ResponseBody
public AjaxResult export()
{

List<SysRole> list = new ArrayList<SysRole>();
    // List<SysRole> list = hxDayReportService.getMonthReport(month);
        ExcelUtil<SysRole> util = new ExcelUtil<SysRole>(SysRole.class);
            return util.exportExcel(list, "2019-08-31"+" 工时统计报表");
            }*/
    @GetMapping("/exportMonthCal/{month}")
    @ResponseBody
    public AjaxResult exportMonthCal(@PathVariable("month") String month) throws Exception {
        //获得Excel文件输出流
        String downloadpath = Global.getDownloadPath();
        FileOutputStream out = new FileOutputStream(new File(downloadpath + "/" + month + "工时统计表.xls"));
        //创建excel工作簿对象
        //HSSFWorkbook wb = new HSSFWorkbook();
        XSSFWorkbook wb = new XSSFWorkbook();
        //创建excel页
        XSSFSheet sheet = wb.createSheet(month + "工时统计表");

        XSSFCellStyle headStyle = setHeadStyle(wb);
        XSSFCellStyle head1Style = setHead1Style(wb);
        XSSFCellStyle head2Style = setHead2Style(wb);
        XSSFCellStyle style = setContentStyle(wb);

        //获取数据
        Map<String, Object> map = hxDayReportService.getMonthCal(month);
        List<HxProject> yfxm = (List<HxProject>) map.get("yfxm");
        List<HxProject> zhxm = (List<HxProject>) map.get("zhxm");
        List<HxProject> qtxm = (List<HxProject>) map.get("qtxm");
        int length_ = 0;
        length_ = yfxm.size() + zhxm.size() + qtxm.size();

        //固定表头
        sheet.createFreezePane(4, 4);

        //设置列宽
        for (int i = 0; i < length_ + 11; i++) {
            if (i < 4 || i > length_ + 3) {
                sheet.setColumnWidth(i, 3000);
            } else {
                sheet.setColumnWidth(i, 5000);
            }
        }

        //row0
        XSSFRow row0 = sheet.createRow(0);
        row0.setHeight((short) 500);
        //sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 3));   //第1行的第1~4列合并
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, length_ + 12));
        String monthArr[] = month.split("-");
        String month_ = monthArr[0] + "年" + monthArr[1] + "月研发中心人员工时汇总表";
        setCellDefaultStyle(month_, headStyle, row0.createCell(0));

        //row1
        XSSFRow row1 = sheet.createRow(1);
        row1.setHeight((short) 500);
        sheet.addMergedRegion(new CellRangeAddress(1, 2, 0, 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 4, length_ + 3));
        sheet.addMergedRegion(new CellRangeAddress(1, 2, length_ + 4, length_ + 10));
        sheet.addMergedRegion(new CellRangeAddress(1, 2, length_ + 11, length_ + 12));
        setCellDefaultStyle("", head1Style, row1.createCell(0));
        setCellDefaultStyle("开展项目投入工作量（天）", head1Style, row1.createCell(4));
        setCellDefaultStyle("项目外投入", head1Style, row1.createCell(length_ + 4));

        //row2
        XSSFRow row2 = sheet.createRow(2);
        row2.setHeight((short) 500);
        //sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 3));
        if (yfxm.size() > 1) {
            sheet.addMergedRegion(new CellRangeAddress(2, 2, 4, 3 + yfxm.size()));
        }
        if (zhxm.size() > 1) {
            sheet.addMergedRegion(new CellRangeAddress(2, 2, yfxm.size() + 4, yfxm.size() + 3 + zhxm.size()));
        }
        if (qtxm.size() > 1) {
            sheet.addMergedRegion(new CellRangeAddress(2, 2, yfxm.size() + 4 + zhxm.size(), yfxm.size() + 3 + zhxm.size() + qtxm.size()));
        }
        setCellDefaultStyle("研发项目", head1Style, row2.createCell(4));
        setCellDefaultStyle("综合项目", head1Style, row2.createCell(yfxm.size() + 4));
        setCellDefaultStyle("其他项目", head1Style, row2.createCell(yfxm.size() + 4 + zhxm.size()));

        //row3
        XSSFRow row3 = sheet.createRow(3);
        row3.setHeight((short) 1500);
        setCellDefaultStyle("姓名", head2Style, row3.createCell(0));
        setCellDefaultStyle("组别", head2Style, row3.createCell(1));
        setCellDefaultStyle("职位", head2Style, row3.createCell(2));
        setCellDefaultStyle("公司", head2Style, row3.createCell(3));
        int z = 3;
        for (int i = 0; i < yfxm.size(); i++) {
            z = z + 1;
            setCellDefaultStyle(yfxm.get(i).getProname(), head2Style, row3.createCell(z));
        }
        for (int i = 0; i < zhxm.size(); i++) {
            z = z + 1;
            setCellDefaultStyle(zhxm.get(i).getProname(), head2Style, row3.createCell(z));
        }
        for (int i = 0; i < qtxm.size(); i++) {
            z = z + 1;
            setCellDefaultStyle(qtxm.get(i).getProname(), head2Style, row3.createCell(z));
        }
        setCellDefaultStyle("技术支持", head2Style, row3.createCell(z + 1));
        setCellDefaultStyle("工程变更", head2Style, row3.createCell(z + 2));
        setCellDefaultStyle("项目申报", head2Style, row3.createCell(z + 3));
        setCellDefaultStyle("商务合作", head2Style, row3.createCell(z + 4));
        setCellDefaultStyle("部门管理", head2Style, row3.createCell(z + 5));
        setCellDefaultStyle("软件临时任务", head2Style, row3.createCell(z + 6));
        setCellDefaultStyle("其他", head2Style, row3.createCell(z + 7));
        setCellDefaultStyle("合计", head1Style, row3.createCell(z + 8));
        setCellDefaultStyle("备注", head1Style, row3.createCell(z + 9));

        //row data
        List<HxDayReportView> list_data = (List<HxDayReportView>) map.get("list");
        for (int i = 0; i < list_data.size(); i++) {
            XSSFRow row_data = sheet.createRow(4 + i);
            row_data.setHeight((short) 500);
            //前四列
            setCellDefaultStyle(list_data.get(i).getUserName(), style, row_data.createCell(0));
            setCellDefaultStyle(list_data.get(i).getDeptName(), style, row_data.createCell(1));
            setCellDefaultStyle(list_data.get(i).getPosition(), style, row_data.createCell(2));
            setCellDefaultStyle(list_data.get(i).getGsName(), style, row_data.createCell(3));

            //开展项目投入工作量（天）
            Map<String, Object> map_data = list_data.get(i).getMap();
            int y = 3;
            for (int j = 0; j < yfxm.size(); j++) {
                y = y + 1;
                if (map_data.get(yfxm.get(j).getProname()) != null && map_data.get(yfxm.get(j).getProname()) != "") {
                    double work_time = deciMal((Double) map_data.get(yfxm.get(j).getProname()), 7.5);
                    setCellDefaultStyle(work_time, style, row_data.createCell(y));
                } else {
                    setCellDefaultStyle(0, style, row_data.createCell(y));
                }
            }
            for (int j = 0; j < zhxm.size(); j++) {
                y = y + 1;
                if (map_data.get(zhxm.get(j).getProname()) != null && map_data.get(zhxm.get(j).getProname()) != "") {
                    double work_time = deciMal((Double) map_data.get(zhxm.get(j).getProname()), 7.5);
                    setCellDefaultStyle(work_time, style, row_data.createCell(y));
                } else {
                    setCellDefaultStyle(0, style, row_data.createCell(y));
                }
            }
            for (int j = 0; j < qtxm.size(); j++) {
                y = y + 1;
                if (map_data.get(qtxm.get(j).getProname()) != null && map_data.get(qtxm.get(j).getProname()) != "") {
                    double work_time = deciMal((Double) map_data.get(qtxm.get(j).getProname()), 7.5);
                    setCellDefaultStyle(work_time, style, row_data.createCell(y));
                } else {
                    setCellDefaultStyle(0, style, row_data.createCell(y));
                }
            }
            //项目外
            double work_time1 = deciMal(list_data.get(i).getOther_pro1(), 7.5);
            double work_time2 = deciMal(list_data.get(i).getOther_pro2(), 7.5);
            double work_time3 = deciMal(list_data.get(i).getOther_pro3(), 7.5);
            double work_time4 = deciMal(list_data.get(i).getOther_pro4(), 7.5);
            double work_time5 = deciMal(list_data.get(i).getOther_pro5(), 7.5);
            double work_time6 = deciMal(list_data.get(i).getOther_pro6(), 7.5);
            double work_time7 = deciMal(list_data.get(i).getOther_pro7(), 7.5);
            setCellDefaultStyle(work_time1, style, row_data.createCell(y + 1));
            setCellDefaultStyle(work_time2, style, row_data.createCell(y + 2));
            setCellDefaultStyle(work_time3, style, row_data.createCell(y + 3));
            setCellDefaultStyle(work_time4, style, row_data.createCell(y + 4));
            setCellDefaultStyle(work_time5, style, row_data.createCell(y + 5));
            setCellDefaultStyle(work_time7, style, row_data.createCell(y + 6));
            setCellDefaultStyle(work_time6, style, row_data.createCell(y + 7));
            //合计
            double work_time = deciMal((Double) map_data.get("total_work_time"), 7.5);
            setCellDefaultStyle(work_time, style, row_data.createCell(y + 8));
            //备注
            setCellDefaultStyle(list_data.get(i).getRemark(), style, row_data.createCell(y + 9));

        }

        //输出excel的错误形式：
        //out.write(fs.getBytes(), 0, fs.getBytes().length);
        //正确形式：
        wb.write(out);
        //关流
        out.close();
        return AjaxResult.success(month + "工时统计表.xls");

    }

    private double deciMal(double top, double below) {
        double result = new BigDecimal((float) top / below).setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
        return result;
    }

    /**
     * 表头样式
     *
     * @param wb
     * @return XSSFCellStyle
     */
    private static XSSFCellStyle setHeadStyle(XSSFWorkbook wb) {
        XSSFCellStyle headStyle = wb.createCellStyle();
        // 设置背景颜色白色
        //headStyle.setFillForegroundColor(HSSFColor.LIGHT_GREEN.index);
        // 设置填充颜色
        // headStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);

        // 设置水平居中
        headStyle.setAlignment(HorizontalAlignment.CENTER);
        // 设置标题字体
        XSSFFont headFont = wb.createFont();
        headFont.setFontName("华文楷体");
        headFont.setColor(HSSFFont.COLOR_RED);
        headFont.setFontHeightInPoints((short) 20);
        headFont.setBold(true);
        headStyle.setFont(headFont);
        return headStyle;
    }

    /**
     * 副标题1样式
     *
     * @param wb
     * @return XSSFCellStyle
     */
    private static XSSFCellStyle setHead1Style(XSSFWorkbook wb) {
        XSSFCellStyle head1Style = wb.createCellStyle();
        // 设置水平居中
        head1Style.setAlignment(HorizontalAlignment.CENTER);
        head1Style.setVerticalAlignment(VerticalAlignment.CENTER);
        head1Style.setWrapText(true);//自动换行
        // 设置标题字体
        XSSFFont headFont = wb.createFont();
        headFont.setFontName("华文楷体");
        headFont.setFontHeightInPoints((short) 14);
        headFont.setBold(true);
        head1Style.setFont(headFont);
        return head1Style;
    }
    /**
     * 副标题2样式
     *
     * @param wb
     * @return XSSFCellStyle
     */
    private static XSSFCellStyle setHead2Style(XSSFWorkbook wb) {
        XSSFCellStyle head2Style = wb.createCellStyle();
        // 设置水平居中
        head2Style.setAlignment(HorizontalAlignment.CENTER);
        head2Style.setVerticalAlignment(VerticalAlignment.CENTER);
        head2Style.setWrapText(true);//自动换行
        // 设置标题字体
        XSSFFont headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setFontHeightInPoints((short) 12);
        head2Style.setFont(headFont);
        return head2Style;
    }

    /**
     * 内容样式
     *
     * @param wb
     * @return XSSFCellStyle
     */
    private static XSSFCellStyle setContentStyle(XSSFWorkbook wb) {
        XSSFCellStyle contentStyle = wb.createCellStyle();
        contentStyle.setVerticalAlignment(VerticalAlignment.CENTER);
        contentStyle.setWrapText(true);//自动换行
        // 设置标题字体
        XSSFFont headFont = wb.createFont();
        headFont.setFontName("宋体");
        headFont.setFontHeightInPoints((short) 12);
        contentStyle.setFont(headFont);
        return contentStyle;
    }

    private static void setCellDefaultStyle(String value, CellStyle style, Cell cell) {
        cell.setCellStyle(style);
        cell.setCellValue(value);
    }
    
    private static void setCellDefaultStyle(double value, CellStyle style, Cell cell) {
        cell.setCellStyle(style);
        cell.setCellValue(value);
    }


    @GetMapping("/common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = Global.getDownloadPath() + "/" + fileName;

            response.setCharacterEncoding("utf-8");
            response.setContentType("multipart/form-data");
            response.setHeader("Content-Disposition",
                    "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    @GetMapping("/monthCal")
    @ResponseBody
    public Map<String, Object> getMonthCal(String month) {
        return hxDayReportService.getMonthCal(month);

    }

    /**
     * 查询日报列表
     */
    @RequiresPermissions("system:hxDayReport:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HxDayReport hxDayReport) {
    	//String beginTime = (String) hxDayReport.getParams().get("beginTime");
    	if(hxDayReport.getUserId() == null) {
    		 SysUser user = ShiroUtils.getSysUser();
    		 hxDayReport.setUserId(user.getUserId());
    	}
        startPage();
        List<HxDayReport> list = hxDayReportService.selectHxDayReportList(hxDayReport);
        return getDataTable(list);
    }


    /**
     * 查询当前月   日报
     */
    //@RequiresPermissions("system:hxDayReport:list")
    @PostMapping("/listDaysReport")
    @ResponseBody
    public TableDataInfo listCurrentMonth(HxDayReport hxDayReport) {
        startPage();
        SysUser user = ShiroUtils.getSysUser();
        hxDayReport.setUserId(user.getUserId());
        List<HxDayReport> list = hxDayReportService.selectDayReport(hxDayReport);
        return getDataTable(list);
    }


    /**
     * 导出日报列表
     */
    @RequiresPermissions("system:hxDayReport:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HxDayReport hxDayReport) {
        List<HxDayReport> list = hxDayReportService.selectHxDayReportList(hxDayReport);
        ExcelUtil<HxDayReport> util = new ExcelUtil<HxDayReport>(HxDayReport.class);
        return util.exportExcel(list, "hxDayReport");
    }


    /**
     * 新增日报
     */
    @GetMapping("/add")
    public String add(ModelMap mmap, String dateStr) {

        SysUser user = ShiroUtils.getSysUser();
        if (!StringUtils.isEmpty(dateStr)) {
            String[] dateArr = dateStr.split("-");
            String year = dateArr[0];
            String month = dateArr[1];
            String day = dateArr[2];
            if (Integer.parseInt(month) < 10) {
                month = "0" + month;
            }
            if (Integer.parseInt(day) < 10) {
                day = "0" + day;
            }
            dateStr = year + "-" + month + "-" + day;
        }
        HxProject hxProject = new HxProject();
        hxProject.setParticipators(user.getUserId().toString());
        hxProject.setStatus(1);//只能选择进行中的项目
        List<HxProject> list = hxProjectService.selectHxProjectList(hxProject);
        //mmap.put("projects", hxProjectService.selectParticipatedProjectList(Long.toString(user.getUserId())));
        mmap.put("projects", list);
        mmap.put("dateStr", dateStr);
        return prefix + "/add";
    }


    /**
     * 日报查看
     */
    @GetMapping("/viewToday")
    public String viewToday(ModelMap mmap, String dateStr) {

        SysUser user = ShiroUtils.getSysUser();
        if (!StringUtils.isEmpty(dateStr)) {
            String[] dateArr = dateStr.split("-");
            String year = dateArr[0];
            String month = dateArr[1];
            String day = dateArr[2];
            if (Integer.parseInt(month) < 10) {
                month = "0" + month;
            }
            if (Integer.parseInt(day) < 10) {
                day = "0" + day;
            }
            dateStr = year + "-" + month + "-" + day;
        }
        HxDayReport hxDayReport = new HxDayReport();
        mmap.put("todayReports", hxDayReportService.selectTodayReportList(hxDayReport));
        mmap.put("dateStr", dateStr);
        return prefix + "/view_today";
    }

    /**
     * 新增保存日报
     */
    @RequiresPermissions("system:hxDayReport:add")
    @Log(title = "日报", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(HxDayReport hxDayReport) {
        if (hxDayReport.getWorkType().equals("2")) {
            hxDayReport.setProjectId(Long.parseLong(hxDayReport.getExceptProjectType()));
        }

        String workTime = String.valueOf(hxDayReport.getWorkTime());
        String[] workTimeArr = workTime.split("\\.");
        if (!workTimeArr[1].equals("5")) {
            hxDayReport.setWorkTime(Double.parseDouble(workTimeArr[0]));
        }
        SysUser user = ShiroUtils.getSysUser();
        hxDayReport.setUserId(user.getUserId());
        hxDayReport.setDeptId(user.getDeptId());
        hxDayReport.setCreateDate(new Date());
        hxDayReport.setUpdateDate(new Date());
        return toAjax(hxDayReportService.insertHxDayReport(hxDayReport));
    }

    /**
     * 修改日报页面
     */
    @GetMapping("/editOne")
    public String editOne(String dateStr, Long projectId, ModelMap mmap) {
        HxDayReport hxDayReport = new HxDayReport();
        SysUser user = ShiroUtils.getSysUser();
        hxDayReport.setUserId(user.getUserId());
        hxDayReport.setWorkDate(DateUtils.parseDate(dateStr));
        hxDayReport.setProjectId(projectId);
        List<HxDayReport> list = hxDayReportService.selectDayReport(hxDayReport);
        mmap.put("projects", hxProjectService.selectParticipatedProjectList(Long.toString(user.getUserId())));
        mmap.put("hxDayReport", list.get(0));
        return prefix + "/edit_one";
    }


    /**
     * 修改保存日报
     */
    @RequiresPermissions("system:hxDayReport:edit")
    @Log(title = "日报", businessType = BusinessType.UPDATE)
    @PostMapping("/editOneSave")
    @ResponseBody
    public AjaxResult editOneSave(HxDayReport hxDayReport) {
        HxDayReport updateDayReport = hxDayReportService.selectHxDayReportById(hxDayReport.getId());
        updateDayReport.setWorkTime(hxDayReport.getWorkTime());

        String workTime = String.valueOf(hxDayReport.getWorkTime());
        String[] workTimeArr = workTime.split("\\.");
        if (!workTimeArr[1].equals("5")) {
            updateDayReport.setWorkTime(Double.parseDouble(workTimeArr[0]));
        }
        //System.out.println(workTimeArr[1]);
        updateDayReport.setWorkDesc(hxDayReport.getWorkDesc());

        updateDayReport.setUpdateTime(new Date());
        return toAjax(hxDayReportService.updateHxDayReport(updateDayReport));
    }

                                                    /*	@GetMapping("/edit/{id}")
                                                    public String edit(@PathVariable("id") Integer id, ModelMap mmap)
                                                    {
                                                    HxDayReport hxDayReport = hxDayReportService.selectHxDayReportById(id);
                                                    mmap.put("hxDayReport", hxDayReport);
                                                    return prefix + "/edit";
                                                    }*/


    /**
     * 修改保存日报
     */
    @RequiresPermissions("system:hxDayReport:edit")
    @Log(title = "日报", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(HxDayReport hxDayReport) {
        return toAjax(hxDayReportService.updateHxDayReport(hxDayReport));
    }

    /**
     * 删除日报
     */
    @RequiresPermissions("system:hxDayReport:remove")
    @Log(title = "日报", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        return toAjax(hxDayReportService.deleteHxDayReportByIds(ids));
    }

}
